package cn.maihe.elg.operation.service.order;

import cn.maihe.elg.operation.model.enums.AttachmentFileType;
import cn.maihe.elg.operation.repository.entity.AcceptOrderInfoDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeAttachmentInfoDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeAttachmentInfoDOCondition;
import cn.maihe.elg.operation.service.BaseDaoService;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import cn.maihe.elg.operation.utils.IdGenerate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.File;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Date;
import java.util.List;

/**
 * @Description
 * @Author WJH
 * @Date 2021/04/27
 */
@Service
public class GuaranteeAttachmentInfoService extends BaseDaoService<GuaranteeAttachmentInfoDO> {

    @Resource
    private ElgResourceService elgResourceService;

    public void saveOrUpdateAttachmentInfoList(List<GuaranteeAttachmentInfoDO> list, String acceptOrderNo) {
        if (list != null) {
            list.stream().map(v -> {
                v.setAcceptOrderNo(acceptOrderNo);
                return v;
            }).forEach(this::saveOrUpdateAttachmentInfo);
        }
    }


    public void saveOrUpdateAttachmentInfo(GuaranteeAttachmentInfoDO cur) {
        GuaranteeAttachmentInfoDO dbDo = get(cur.getCenterId(), cur.getOrgId(), cur.getAcceptOrderNo(), AttachmentFileType.resolve(cur.getType()));
        if (dbDo != null) {
            cur.setId(dbDo.getId());
            cur.setGmtModified(Date.from(Instant.now()));
            this.updateById(cur);
        } else {
            cur.setId(cur.getId() != null ? cur.getId() : IdGenerate.getId());
            cur.setGmtCreate(Date.from(Instant.now()));
            cur.setGmtModified(cur.getGmtCreate());
            this.insert(cur);
        }
    }


    public GuaranteeAttachmentInfoDO get(Long centerId, Long orgId, String acceptOrderNo, AttachmentFileType type) {
        Assert.notNull(centerId, () -> "centerId不能为空");
        Assert.notNull(orgId, () -> "orgId不能为空");
        Assert.hasText(acceptOrderNo, () -> "acceptOrderNo不能为空");
        Assert.notNull(type, () -> "type不能为空");

        //保函附件一个type唯一一个文件
        return this.selectOne(GuaranteeAttachmentInfoDOCondition.builder().andCenterIdEq(centerId).andOrgIdEq(orgId)
                .andAcceptOrderNoEq(acceptOrderNo).andTypeEq(type.getType()).build());
    }

    public List<GuaranteeAttachmentInfoDO> getAllAttachmentByAcceptOrderNo(String acceptOrderNo) {
        List<GuaranteeAttachmentInfoDO> list = this.selectList(GuaranteeAttachmentInfoDOCondition.builder().andAcceptOrderNoEq(acceptOrderNo).build());
        return list;
    }

    public GuaranteeAttachmentInfoDO getTypeAttachmentByAcceptOrderNo(String acceptOrderNo, AttachmentFileType type) {
        GuaranteeAttachmentInfoDO curDO = this.selectOne(GuaranteeAttachmentInfoDOCondition.builder().andAcceptOrderNoEq(acceptOrderNo).andTypeEq(type.getType()).build());
        return curDO;
    }
    /**
     * 存在则返回Path，其他均返回Null，调用者自行判断处理后续业务
     */
    public Path getGuaAttPathNoAuth(String acceptOrderNo, AttachmentFileType type) {
        GuaranteeAttachmentInfoDO curDO = this.selectOne(GuaranteeAttachmentInfoDOCondition.builder().andAcceptOrderNoEq(acceptOrderNo).andTypeEq(type.getType()).build());
        if (curDO == null || StringUtils.isEmpty(curDO.getFilePath())) {
            return null;
        }
        File file = elgResourceService.getFileByRelativePath(curDO.getFilePath());
        if (!file.exists()) {
            return null;
        }
        return file.toPath();
    }
    public Path getGuaAttPath(String acceptOrderNo, AttachmentFileType type) {
        GuaranteeAttachmentInfoDO curDO = this.selectOne(GuaranteeAttachmentInfoDOCondition.builder().andAcceptOrderNoEq(acceptOrderNo).andTypeEq(type.getType()).build());
        Assert.notNull(curDO,()->"查无此附件[" + type.getDesc() + "]记录");
        File file = elgResourceService.getFileByRelativePath(curDO.getFilePath());
        Assert.isTrue(file.exists(), () -> "附件[" + type.getDesc() + "]不存在");
        return file.toPath();
    }

    public GuaranteeAttachmentInfoDO saveOrUpdateAttachmentInfo(AcceptOrderInfoDO orderInfo, Path attachPath, AttachmentFileType type, String remark) {
        GuaranteeAttachmentInfoDO infoDO = GuaranteeAttachmentInfoDO.builder()
                .centerId(orderInfo.getCenterId()).orgId(orderInfo.getOrgId())
                .acceptOrderNo(orderInfo.getAcceptOrderNo())
                .fileName(elgResourceService.getFileName(attachPath))
                .fileType(elgResourceService.getFileType(attachPath))
                .filePath(elgResourceService.getRelativePath(attachPath))
                .fileMd5(elgResourceService.getFileMD5AsHex(attachPath))
                .type(type.getType()).remark(remark)
                .build();
        saveOrUpdateAttachmentInfo(infoDO);
        return infoDO;
    }

    public String buildAttachDownloadUrl(String acceptOrderNo, AttachmentFileType attachmentFileType) {
        GuaranteeAttachmentInfoDO attachmentInfoDO = this.getTypeAttachmentByAcceptOrderNo(acceptOrderNo, attachmentFileType);
        if (attachmentInfoDO != null) {
            try {
                String encodeRelativeUrl = elgResourceService.fmtNoAuthDownloadUrl(attachmentInfoDO.getFilePath());
                return encodeRelativeUrl;
            } catch (Exception e) {
                throw new RuntimeException("获取附件下载地址错误:" + e.getMessage(), e);
            }
        }
        return null;
    }
}
